import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { IUserResponse, ILoginRequest, IRegisterRequest } from '@/types'
import { login as apiLogin, register as apiRegister, logout as apiLogout, getCurrentUser } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const user = ref<IUserResponse | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isLoggedIn = computed(() => !!token.value && !!user.value)

  // 登录
  const login = async (loginData: ILoginRequest) => {
    try {
      const response = await apiLogin(loginData)
      if (response.success) {
        user.value = response.data.user
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return { success: true, message: response.message }
      }
      return { success: false, message: response.message }
    } catch (error: any) {
      return { success: false, message: error.response?.data?.message || '登录失败' }
    }
  }

  // 注册
  const register = async (userData: IRegisterRequest) => {
    try {
      const response = await apiRegister(userData)
      if (response.success) {
        user.value = response.data.user
        token.value = response.data.token
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('user', JSON.stringify(response.data.user))
        return { success: true, message: response.message }
      }
      return { success: false, message: response.message }
    } catch (error: any) {
      return { success: false, message: error.response?.data?.message || '注册失败' }
    }
  }

  // 登出
  const logout = async () => {
    try {
      await apiLogout()
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      user.value = null
      token.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  }

  // 初始化用户信息
  const initUser = async () => {
    const savedUser = localStorage.getItem('user')
    const savedToken = localStorage.getItem('token')

    if (savedUser && savedToken) {
      user.value = JSON.parse(savedUser)
      token.value = savedToken

      // 验证 token 是否有效
      try {
        const response = await getCurrentUser()
        if (response.success) {
          user.value = response.data
        }
      } catch (error) {
        // Token 无效，清除本地存储
        logout()
      }
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    login,
    register,
    logout,
    initUser
  }
})
